import axios from 'axios';
axios.defaults.baseURL = 'http://127.0.0.1:3000';

axios.interceptors.request.use(config=>{
    let accessToken = localStorage.getItem('accessToken');
    if(accessToken){
        config.headers['authorization'] = accessToken;
    }
    return config;
})

axios.interceptors.response.use(
    config=>{
        return config;
    },
    async error=>{
        console.log(error);
        let {status,date,config} = error.response
        if(status == 601 && !config.url.includes('/getNewToken')){
            let res = await axios.post('/szh/getNewToken',{refreshToken:localStorage.getItem('refreshToken')})
            if(res.status == 200 && res.data.code==200){
                localStorage.setItem('accessToken',res.data.accessToken)
                localStorage.setItem('refreshToken',res.data.refreshToken)
                console.log(res.data.msg);
                return axios(config)
            }else{
                localStorage.removeItem('accessToken')
                localStorage.removeItem('refreshToken')
                return {}
            }
        }else{
            return error            
        }
    }
    
)

export default axios;